package com.behome.socket_proxy;

import com.behome.socket_proxy.netty_D.Constants;
import com.behome.socket_proxy.netty_D.server.StandardDNettyServer;
import lombok.extern.slf4j.Slf4j;

import java.util.Arrays;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Slf4j
public class timeTask  implements Runnable{
    static final ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);


    public void start(){
        executorService.scheduleAtFixedRate(this, 0, 200, TimeUnit.MILLISECONDS);
    }

    @Override
    public void run() {
        try {
            task();
        } catch (Exception e) {
            log.error("热备服务器判断出现异常: {}" , Arrays.toString(e.getStackTrace()));
        }
    }

    public void task() throws InterruptedException {
        boolean flag1 = new TcpClient().connectResult(Constants.proxy1,Constants.port);
        boolean flag2 = new TcpClient().connectResult(Constants.proxy2,Constants.port);
        int serverConnectNum = 2;
        if (!flag1) {
            serverConnectNum--;
        }
        if (!flag2) {
            serverConnectNum--;
        }
        if (serverConnectNum == 0 && StandardDNettyServer.flag) {
            StandardDNettyServer.getInstance().stop();
        } else if (serverConnectNum != 0 && !StandardDNettyServer.flag) {
            StandardDNettyServer.getInstance().start();
        }
    }
}
